package com.lanou3g.zjl.chating.home.widget;

import android.content.Intent;
import android.graphics.Bitmap;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.easemob.chat.EMChatManager;
import com.easemob.chat.EMContactManager;
import com.easemob.exceptions.EaseMobException;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.lanou3g.zjl.chating.R;
import com.lanou3g.zjl.chating.base.BaseActivity;
import com.zbar.lib.CaptureActivity;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;

/**
 * Created by dllo on 15/12/2.
 */
public class AddFriendsByQRCode extends BaseActivity {
    int QR_WIDTH = 600;
    int QR_HEIGHT = 600;

    @Bind(R.id.showQR)
    ImageView showQR;
    @Bind(R.id.resultTv)
    TextView resultTv;

    @Override
    protected int getLayout() {
        return R.layout.activity_qr_code;
    }

    @Override
    protected void initData() {
        //加载时生成二维码
        JSONObject json = new JSONObject();
        try {
            json.put("name", EMChatManager.getInstance().getCurrentUser());

            createImage(json.toString());

        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    //扫描二维码界面
    @OnClick(R.id.searchQR)
    void searchQR() {
        Intent intent = new Intent(AddFriendsByQRCode.this, CaptureActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivityForResult(intent, 1);
    }
    @OnClick(R.id.finishQR) void finishQR(){
        finish();
    }
    // 生成QR图
    private void createImage(String content) {
        try {
            // 把输入的文本转为二维码
            Hashtable<EncodeHintType, String> hints = new Hashtable<EncodeHintType, String>();
            hints.put(EncodeHintType.CHARACTER_SET, "utf-8");

            BitMatrix bitMatrix = new QRCodeWriter().encode(content,
                    BarcodeFormat.QR_CODE, QR_WIDTH, QR_HEIGHT, hints);

            int[] pixels = new int[QR_WIDTH * QR_HEIGHT];
            for (int y = 0; y < QR_HEIGHT; y++) {
                for (int x = 0; x < QR_WIDTH; x++) {
                    if (bitMatrix.get(x, y)) {
                        pixels[y * QR_WIDTH + x] = 0xff000000;
                    } else {
                        pixels[y * QR_WIDTH + x] = 0xffffffff;
                    }

                }
            }

            Bitmap bitmap = Bitmap.createBitmap(QR_WIDTH, QR_HEIGHT,
                    Bitmap.Config.ARGB_8888);

            bitmap.setPixels(pixels, 0, QR_WIDTH, 0, 0, QR_WIDTH, QR_HEIGHT);
            if (bitmap != null) {
                showQR.setImageBitmap(bitmap);
            }

        } catch (WriterException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        super.onActivityResult(requestCode, resultCode, data);

        if(data != null){
            String qr = data.getStringExtra("result");
            String showResult = null;
            try {
                JSONObject json = new JSONObject(qr);
                showResult = json.getString("name");
            } catch (JSONException e) {
                e.printStackTrace();
            }
            addFriends(showResult);
            resultTv.setText(showResult);
        }

    }
    //发送好友请求的方法
    private void addFriends(final String name){
        //输入的是自己用户名则不能添加
        if(EMChatManager.getInstance().getCurrentUser().equals(name)){
            Toast.makeText(this, "不能添加自己为好友", Toast.LENGTH_SHORT).show();
            return;
        }
        List<String> newFriends = new ArrayList<>();
        EMChatManager.getInstance().getChatOptions().setUseRoster(true);
        try {
            newFriends = EMContactManager.getInstance().getContactUserNames();
        } catch (EaseMobException e) {
            e.printStackTrace();
        }

        if(newFriends.contains(name)){
            //提示已在好友列表中(在黑名单列表里)，无需添加
            if(EMContactManager.getInstance().getBlackListUsernames().contains(name)){
                Toast.makeText(this,"该用户已在你的黑名单中",Toast.LENGTH_SHORT).show();
                return;
            }
            Toast.makeText(this,"该好友已存在",Toast.LENGTH_SHORT).show();
            return;
        }
        new Thread(new Runnable() {
            public void run() {

                try {
                    EMContactManager.getInstance().addContact(name, "加个好友吧!!!");

                    runOnUiThread(new Runnable() {
                        public void run() {

                            Toast.makeText(getApplicationContext(), "请求发送成功,等待验证!!", Toast.LENGTH_LONG).show();
                        }
                    });
                } catch (final Exception e) {

                    runOnUiThread(new Runnable() {
                        public void run() {
                            Toast.makeText(getApplicationContext(), "请求发送失败" + e.getMessage(), Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            }
        }).start();
    }
}
